package me.leiusual.sharing.ui.home

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.activityViewModels
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_home_search_product.*
import me.leiusual.sharing.R
import me.leiusual.sharing.ui.MainViewModel
import me.leiusual.sharing.ui.home.adapter.HomeSearchProductAdapter
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-30
 * description:
 */
class HomeSearchProductFragment : DaggerFragment() {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val mainViewModel: MainViewModel by activityViewModels { factory }

  private val viewModel: HomeSearchProductViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_home_search_product, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    recycler_view.adapter = HomeSearchProductAdapter {
      Timber.v("点击：%s", it)

      // 导航到商品详情
      val action = HomeSearchFragmentDirections.actionHomeSearchFragmentToProductDetailFragment(it.miaId, it.curStoreId)
      findNavController().navigate(action)
    }

    observeData()
  }

  private fun observeData() {
    mainViewModel.searchKeyword.observe(viewLifecycleOwner, Observer {
      Timber.v("searchKeyword = %s", it)

      // 搜索
      it?.let {
        viewModel.productSearch(it, viewModel.store.currentStoreId)
      }
    })

    viewModel.productSearch.observe(viewLifecycleOwner, Observer {
      Timber.v("productSearch = %s", it)

      // 刷新
      val adapter = recycler_view.adapter as HomeSearchProductAdapter
      adapter.submitList(it)
    })
  }
}